//
//  WZHString.swift
//  TCMHealth
//
//  Created by 韩颖 on 2023/7/2.
//

import Foundation
import UIKit
import CommonCrypto


// 计算文字高度或者宽度与weight参数无关
extension String {
    
    /**
     计算文字高度，允许换行计算

     @param fontSize 文字大小
     @param widht 文字宽度
     @return 返回文字的高度
     */
    
    func sizeLineFeedWithFont(fontSize:CGFloat,width:CGFloat) -> CGFloat {
        let textView = UITextView(frame: CGRect(x: 0, y: 0, width: width, height: 0))
        textView.text = self
        textView.font = UIFont.systemFont(ofSize: fontSize)
        let size = CGSize(width: width, height: CGFloat(MAXFLOAT))
        let constraint = textView.sizeThatFits(size)
        let height = constraint.height > 40 ? constraint.height : 40
        return height
    }

    //计算宽度
    func ga_widthForComment(fontSize: CGFloat, height: CGFloat = 30) -> CGFloat {
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = NSString(string: self).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: height), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.width)
    }

    //计算高度
    func ga_heightForComment(fontSize: CGFloat, width: CGFloat) -> CGFloat {
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.height)
    }

    //计算高度限制在最大高度内
    func ga_heightForComment(fontSize: CGFloat, width: CGFloat, maxHeight: CGFloat) -> CGFloat {
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return ceil(rect.height)>maxHeight ? maxHeight : ceil(rect.height)
    }
    
    //计算带行间距的高度
    func ga_heightForComment(fontSize: CGFloat, width: CGFloat,lineSpacing:CGFloat) -> CGFloat {
        let paraStyle = NSMutableParagraphStyle()
        paraStyle.lineSpacing = lineSpacing
        paraStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
        paraStyle.paragraphSpacing = 0
        paraStyle.paragraphSpacingBefore = 0
        let font = UIFont.systemFont(ofSize: fontSize)
        let rect = NSString(string: self).boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font,NSAttributedString.Key.paragraphStyle:paraStyle], context: nil)
        return ceil(rect.height)
    }

    //计算
    public func getStringSize(rectSize: CGSize,font: UIFont) -> CGSize {
        let str: NSString = self as NSString
        let rect = str.boundingRect(with: rectSize, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSAttributedString.Key.font: font], context: nil)
        return CGSize(width: ceil(rect.width), height: ceil(rect.height))
    }

}

extension String {
    // MARK: 字符串转字典
    func stringToDictionary(_ str: String) -> [String : Any]?{
        let data = str.data(using: String.Encoding.utf8)
        if let dict = try? JSONSerialization.jsonObject(with: data!,options: .mutableContainers) as? [String : Any] {
            return dict
        }

        return nil
    }
    
    func stringToDictionary() -> [String : Any]?{
        let data = self.data(using: String.Encoding.utf8)
        if let dict = try? JSONSerialization.jsonObject(with: data!,options: .mutableContainers) as? [String : Any] {
            return dict
        }

        return nil
    }
    
    func toDictionary() -> [String : Any] {
        var result = [String : Any]()
        guard !self.isEmpty else { return result }

        guard let dataSelf = self.data(using: .utf8) else {
            return result
        }

        if let dic = try? JSONSerialization.jsonObject(with: dataSelf, options: .mutableContainers) as? [String : Any] {
            result = dic
        }
        
        return result
    }
}


// MARK: - 字符串操作(截取,拼接等)
extension String {
    var md5 : String {
        guard let data = data(using: .utf8) else {
            return self
        }
        var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        
#if swift(>=5.0)
        
        _ = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
            return CC_MD5(bytes.baseAddress, CC_LONG(data.count), &digest)
        }
        
#else
        
        _ = data.withUnsafeBytes { bytes in
            return CC_MD5(bytes, CC_LONG(data.count), &digest)
        }
        
#endif
        
        return digest.map { String(format: "%02x", $0) }.joined()
    }
    
    //Base64编码
    func encodBase64() -> String? {
        let strData = self.data(using: String.Encoding.utf8)
        let base64String = strData?.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
        return base64String
    }

    //Base64解码
    func decodeBase64() -> String? {
        let decodedData = NSData(base64Encoded: self, options: NSData.Base64DecodingOptions.init(rawValue: 0))
        let decodedString = NSString(data: decodedData! as Data, encoding: String.Encoding.utf8.rawValue) as String?
        return decodedString
    }
    
    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else { return nil }
        return String(data: data, encoding: String.Encoding.utf8)
    }
    
    func toBase64() -> String? {
        return Data(self.utf8).base64EncodedString()
    }
 
    ///删除字符串最后一个","字符
    func delLastCharacter() -> String {
      var res = self
//      if hasPrefix(",") { res = substring(from: 1) }
      if res.hasSuffix(",") { res = res.substring(to: res.count - 2)}
      return res
    }
    
    func substring(from: Int?, to: Int?) -> String {
        if let start = from {
            guard start < self.count else {
                return ""
            }
        }
        
        if let end = to {
            guard end >= 0 else {
                return ""
            }
        }
        
        if let start = from, let end = to {
            guard end - start >= 0 else {
                return ""
            }
        }
        
        let startIndex: String.Index
        if let start = from, start >= 0 {
            startIndex = self.index(self.startIndex, offsetBy: start)
        } else {
            startIndex = self.startIndex
        }
        
        let endIndex: String.Index
        if let end = to, end >= 0, end < self.count {
            endIndex = self.index(self.startIndex, offsetBy: end + 1)
        } else {
            endIndex = self.endIndex
        }
        
        return String(self[startIndex ..< endIndex])
    }
    
    func substring(from: Int) -> String {
        return self.substring(from: from, to: nil)
    }
    
    func substring(to: Int) -> String {
        return self.substring(from: nil, to: to)
    }
    
    func substring(from: Int?, length: Int) -> String {
        guard length > 0 else {
            return ""
        }
        
        let end: Int
        if let start = from, start > 0 {
            end = start + length - 1
        } else {
            end = length - 1
        }
        
        return self.substring(from: from, to: end)
    }
    
    func substring(length: Int, to: Int?) -> String {
        guard let end = to, end > 0, length > 0 else {
            return ""
        }
        
        let start: Int
        if let end = to, end - length > 0 {
            start = end - length + 1
        } else {
            start = 0
        }
        
        return self.substring(from: start, to: to)
    }
}

// MARK: - 将含有 html 标签的字符串转为富文本
extension String {
    func handlerHTMLString() -> NSMutableAttributedString? {

        guard let data = self.data(using: .unicode, allowLossyConversion: true) else{
            return nil
        }

        //print("Thread.current\(Thread.current)")
        do {

           let attr = try NSMutableAttributedString(
                         data: data,
                         options:[.documentType: NSAttributedString.DocumentType.html,
                                  .characterEncoding: String.Encoding.utf8.rawValue],
                         documentAttributes: nil)
            attr.gj_addLineSpace(4)
            return attr

        }catch{

            print("convert errot \(error)")
            return nil

        }
    }


    func handlerUnicode() -> String? {
        let str1 = self.replacingOccurrences(of: "\\u", with: "\\U")
        let str2 = str1.replacingOccurrences(of: "\"", with: "\\\"")
        let str3 = "\"".appending(str2).appending("\"")
        guard let data = str3.data(using: .utf8) else { return nil }
        let code = try? PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil) as? String
        return code
    }
    
    func handleHTMLContent() -> String {
        let regular = try? NSRegularExpression(pattern: "<[^>]*>|\n", options: [])
        let string = regular?.stringByReplacingMatches(in: self, options: .reportProgress, range: NSRange(location: 0, length: self.count), withTemplate: "")
        return string ?? ""
    }
    
    // "mat1.gtimg.com/www/icon/favicon2.ico" -> "/mat1.gtimg.com/www/icon/favicon2.ico"
    // "//mat1.gtimg.com/www/icon/favicon2.ico" -> "/mat1.gtimg.com/www/icon/favicon2.ico"
    func handlerURLString() -> String {
        if hasPrefix("//") {
            return self
        } else if hasPrefix("/") {
            return self
        } else {
            return "/" + self
        }
    }
}

// MARK: - 返回带有行间距的富文本
extension String {
    //title:卖家:ID
    //222718 -> 卖家:ID2****8
    func encryptedString(title:String) -> String {
        let prefix = self.substring(to: 0)
        let suffix = self.substring(from: self.count - 1)
        let resultString = title + prefix + "***" + suffix
        return resultString
    }
    
    func attributstring(lineHeight:CGFloat) -> NSAttributedString {
        let graph = NSMutableParagraphStyle()
        graph.lineSpacing = lineHeight
        let attributes = [NSAttributedString.Key.paragraphStyle:graph]
        let attr = NSAttributedString(string: self, attributes: attributes)
        return attr
    }
    
    func getColorAttributstring(length:Int) -> NSAttributedString? {
        guard self.count > length else { return nil }
        let graph = NSMutableParagraphStyle()
        graph.lineSpacing = 2
        let attr = NSMutableAttributedString(string: self)
        attr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor(hex: "#FFDF0D")!], range: NSRange(location: 0, length: length))
        attr.addAttributes([NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 12)], range: NSRange(location: length, length: 1))
        attr.addAttributes([NSAttributedString.Key.paragraphStyle : graph], range: NSRange(location: 0, length: self.count))
        return attr
    }
    
    func changeColorAttributstring(length:Int) -> NSMutableAttributedString {
        let attr = NSMutableAttributedString(string: self)
        var tempRange = NSRange(location: 0, length: 2)
        attr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor(hex: "#7B7F97")!], range: tempRange)
        tempRange.location = 2
        tempRange.length = length
        attr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor(hex: "#FFDF0D")!], range: tempRange)
        tempRange.location = length + 2
        tempRange.length = self.count - length - 2
        attr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor(hex: "#7B7F97")!], range: tempRange)
        return attr
    }
}

//正则校验
extension String {
    //验证邮箱
    func validateEmail() -> Bool {
        guard self.count != 0 else { return false }
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let emailTest:NSPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
//        print(emailTest.evaluate(with: self))
        return emailTest.evaluate(with: self)
    }
    
    //验证手机号
    func validatePhoneNumber() -> Bool {
        guard self.count != 0 else { return false }
//        let mobile = "^1([358][0-9]|4[579]|6[256]|7[0135678]|9[125689])[0-9]{8}$"
        //修改正则
        let mobile = "^1([3456789])[0-9]{9}$"

        let regexMobile = NSPredicate(format: "SELF MATCHES %@",mobile)
        return regexMobile.evaluate(with: self) == true
    }
       
    //密码正则  8-16位字母和数字组合
    func validatePassword() -> Bool {
       let passwordRule = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$"
       let regexPassword = NSPredicate(format: "SELF MATCHES %@",passwordRule)
       return regexPassword.evaluate(with: self) == true
    }
}

//正则匹配
extension String {
    ///返回带有数字颜色的富文本
    func highlightDigitalAttributed(color:UIColor? = nil) -> NSMutableAttributedString? {
        return highlightAttributed(content: "(\\d*)",color: color)
    }
    
    func highlightAttributed(color:UIColor?) -> NSMutableAttributedString {
        let attr = self.gj_toAttribute()
        if let cor = color{
            attr.gj_color(cor)
        }
        return attr
    }
    
    //content: 正则表达式
    func highlightAttributed(content:String,color:UIColor? = UIColor(hex: "#FF0000")!) -> NSMutableAttributedString? {
        let strM = NSMutableAttributedString(string: self)
        do {
            //1. 创建规则
            let pattern = content
            //2. 创建正则对象
            let regax = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            let res = regax.matches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange.init(location: 0, length: self.count))
            //遍历
            for i in 0..<res.count {
                let subStr = res[i]
                strM.addAttributes([NSAttributedString.Key.foregroundColor : color ?? UIColor(hex: "#FF0000")!], range: subStr.range)
            }
            return strM
        } catch {
            return strM
        }
    }
  
  func matchesForRegexInText(regex: String) -> [String] {
      do {
          let regex = try NSRegularExpression(pattern: regex, options: [])
          let results = regex.matches(in: self,options: [], range:NSRange(location: 0, length: self.count))
          return results.map({self.substring(from: $0.range.location, to: $0.range.length)})
      } catch let error as NSError {
          print("invalid regex: \(error.localizedDescription)")
          return []
      }
  }
    
    func matchLink() -> NSAttributedString{
        let strM = NSMutableAttributedString(string: self)
        do {
            //1. 创建规则
            let pattern = "(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"
            //2. 创建正则对象
            let regax = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
            let res = regax.matches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange.init(location: 0, length: self.count))
            //遍历
            for i in 0..<res.count {
                let subStr = res[i]
                let resutl = substring(from: subStr.range.location, length: subStr.range.length)
//                print("result === \(resutl)")
                strM.addAttributes([NSAttributedString.Key.foregroundColor : UIColor(hex: "#FF0000")!], range: subStr.range)
            }
            
            return strM
        } catch {
            return strM
        }
    }
 
    //匹配url
    func getHrefString() -> String {
        var result = ""
        // 创建一个正则表达式对象
        do {
            let val = NSTextCheckingResult.CheckingType.link.rawValue
            let dataDetector = try  NSDataDetector (types:val)
            // 匹配字符串，返回结果集
            let res = dataDetector.matches(in: self,options:  NSRegularExpression.MatchingOptions (rawValue: 0),
                range: NSMakeRange (0, self.count))
            // 取出结果
            for i in 0..<res.count {
                let subStr = res[i]
                result = substring(from: subStr.range.location, length: subStr.range.length)
            }
        }
        catch {
            print (error)
        }
        return  result
    }

    func getDigitalWithString() -> String{
      var result:String = ""
      do {
         let pattern = "\\>(.*?)\\<"
         let regax = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
         let res = regax.matches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange.init(location: 0, length: self.count))
         //遍历
         for i in 0..<res.count {
            let subStr = res[i]
            result = self.substring(from: subStr.range.location+1, length: subStr.range.length-2)
//            print("subStr = \(result)")
         }
      }catch {
         print("发生错误")
      }
      
      return result
   }
    
    func replaceSpecialSymbols() -> String{
      var result:String = ""
      do {
         let pattern = "^[\\u4E00-\\u9FFF]+$"
         let regax = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
         let res = regax.matches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange.init(location: 0, length: self.count))
         //遍历
         for i in 0..<res.count {
            let subStr = res[i]
            result = self.substring(from: subStr.range.location+1, length: subStr.range.length-2)
            print("subStr = \(result)")
         }
      }catch {
         print("发生错误")
      }
      
      return result
   }
    
}

extension String {
    /// 字符串转富文本
    func gj_toAttribute() -> NSMutableAttributedString {
        return NSMutableAttributedString(string: self)
    }
    
    func contains(find: String) -> Bool{
        return self.range(of: find) != nil
    }
    
    ///是否为中文开头
    func isChineseHasprefix() -> Bool {
        let str = self as NSString
        for i in 0..<str.length {
            let char = str.character(at: i)
            return (char > 0x4e00 && char < 0x9fff)
        }
        return false
    }
}



extension String {
     //按照索引方式读取字符
     subscript (_ i: Int) -> Character {
         //读取字符
         get { return self[index(startIndex, offsetBy: i)] }
     }
    
    var fileSuffix: String {
        if let index = self.lastIndex(of: ".") {
            return String(self[index...])
        } else {
            return ""
        }
    }
    
     func removeAllSapce() -> String {
         return self.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)
     }

    func replaceAllSapce() -> String {
        return self.replacingOccurrences(of: " ", with: "\n", options: .literal, range: nil)
    }
    
   func jm_contains(_ element:String) -> [String] {
       var tempDomains = [String]()
       if self.contains(find: element) {
           tempDomains = self.components(separatedBy: element)
           tempDomains = tempDomains.filter({$0.count != 0}) //过滤掉空字符串
           return tempDomains
       }else {
         tempDomains.append(self)
       }
      return tempDomains
   }
}

// MARK: 字符串转换
extension String {
    
    ///字符串去空格
    var trim:String{
        //        let whiteSpace = CharacterSet.whitespacesAndNewlines
        //        return self.trimmingCharacters(in: whiteSpace)
        return self.replacingOccurrences(of: " ", with: "")
    }
    /// string 转 int
    var toInt:Int?{
        return Int(self)
    }
    
    var toURL : URL? {
        return URL(string: self)
    }
    
    //获取拼音首字母（大写字母）
    var findFirstLetter : String {
        //转变成可变字符串
        let mutableString = NSMutableString.init(string: self)

        //将中文转换成带声调的拼音
        CFStringTransform(mutableString as CFMutableString, nil,      kCFStringTransformToLatin, false)

        //去掉声调
        let pinyinString = mutableString.folding(options:          String.CompareOptions.diacriticInsensitive, locale:   NSLocale.current)

        //将拼音首字母换成大写
        let strPinYin = polyphoneStringHandle(nameString: self,    pinyinString: pinyinString).uppercased()

        //截取大写首字母
        let firstString = strPinYin.substring(to:     strPinYin.index(strPinYin.startIndex, offsetBy: 1))

        //判断首字母是否为大写
        let regexA = "^[A-Z]$"
        let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
        return predA.evaluate(with: firstString) ? firstString : "#"
    }

    //多音字处理，根据需要添自行加
    func polyphoneStringHandle(nameString: String, pinyinString: String) -> String {
        if nameString.hasPrefix("长") {return "chang"}
        if nameString.hasPrefix("沈") {return "shen"}
        if nameString.hasPrefix("厦") {return "xia"}
        if nameString.hasPrefix("地") {return "di"}
        if nameString.hasPrefix("重") {return "chong"}
        return pinyinString
    }
    
    //MARK: 验证手机号
    
    /// 验证是否是手机号
    var isMobile:Bool{
        let phone = self.trim
        return phone.count >= 11
//        if self.count == 0 {
//            return false
//        }
//        let mobile = "^(13[0-9]|15[0-9]|18[0-9]|17[0-9]|147)\\d{8}$"
//        let regexMobile = NSPredicate(format: "SELF MATCHES %@", mobile)
//        if regexMobile.evaluate(with: self.trim) == true {
//            return true
//        } else {
//            return false
//        }
//        guard self.count != 0 else { return false }
////        let mobile = "^1([358][0-9]|4[579]|6[256]|7[0135678]|9[125689])[0-9]{8}$"
//        //修改正则
//        let mobile = "^1([3456789])[0-9]{9}$"
//
//        let regexMobile = NSPredicate(format: "SELF MATCHES %@",mobile)
//        return regexMobile.evaluate(with: self) == true
    }
    
    ///  加密手机号
    var encryptMobile : String{
        let newCardNum  = self.trim
        guard newCardNum.isMobile else{
            return ""
        }
        let result: String = ( newCardNum as NSString).replacingCharacters(in: NSMakeRange(3, newCardNum.count - 7), with: "****")
        return result
    }
    
    /// 验证邮箱
    var isValidEmail: Bool {
        if self.count == 0 {
            return false
        }
        let mobile = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
        let regexMobile = NSPredicate(format: "SELF MATCHES %@", mobile)
        if regexMobile.evaluate(with: self) == true {
            return true
        } else {
            return false
        }
    }
    
    /// 是否是数字
    var isValidNumber: Bool {
        return NSPredicate(format: "SELF MATCHES %@", "^[0-9]+$").evaluate(with: self)
    }
    
    /// 验证 URL
    var isValidUrl: Bool {
        return URL(string: self) != nil
    }
    
    /// 身份证
    var isIdCard: Bool {
        return NSPredicate(format: "SELF MATCHES %@", "^(\\d{14}|\\d{17})(\\d|[xX])$").evaluate(with: self)
    }
    
    /// 将 html 文本 格式 话
    /// - Returns: 返回一个格式化的 html 文本
    func htmlAdapter() -> String {
        var content = self.replacingOccurrences(of: "&amp;quot", with: "'")
        content = content.replacingOccurrences(of: "&lt;", with: "<")
        content = content.replacingOccurrences(of: "&gt;", with: ">")
        content = content.replacingOccurrences(of: "&quot;", with: "\"")
        
        if content.contains(".mp4"){
            content = content.replacingOccurrences(of: ".mp4", with: ".mp4#t=1")
        }
        
        return "<html> \n  <head> \n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" /> \n <style type=\"text/css\"> \n body {font-size:15px;}\n </style> \n </head> \n <body> <script type='text/javascript'> window.onload = function(){\n var $img = document.getElementsByTagName('img');\n for(var p in  $img){\n $img[p].style.width = '100%%';\n $img[p].style.height ='auto'\n }\n } </script>\(content) </body> </html>"
        
    }
    
    /// 计算字符串rect
    func sizeWithText(font: UIFont, size: CGSize) -> CGRect {
        let attributes = [NSAttributedString.Key.font: font]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let rect:CGRect = self.boundingRect(with: size, options: option, attributes: attributes, context: nil)
        return rect;
    }
    
}

extension String {
    
    // 查找中间字符串
    func subString(prefix: String, tail: String) -> String? {
        
        if self.count == 0 { return nil }
        
        let regex = "(?<=\(prefix)).*?(?=\(tail))"
        let regular = try? NSRegularExpression.init(pattern: regex, options: .caseInsensitive)
        guard let range = regular?.firstMatch(in: self, options: .reportCompletion, range: NSRange(location: 0, length: self.count))?.range else {
            return nil
        }
        
        // 对str字符串进行匹配
        return self.subString(from: range.location, length: range.length)
    }
    
    /// 字符串截取
    func subString(from: Int) -> String {
        let end = self.count
        return String(self[String.Index.init(utf16Offset: from, in: self)..<String.Index.init(utf16Offset: end, in: self)])
    }
    
    func subString(from: Int, length: Int) -> String {
        let end = from + length
        if self.count < end {
            return self
        }
        return String(self[String.Index.init(utf16Offset: from, in: self)..<String.Index.init(utf16Offset: end, in: self)])
    }
    
    func subString(from: Int, to: Int) -> String {
        return String(self[String.Index.init(utf16Offset: from, in: self)..<String.Index.init(utf16Offset: to, in: self)])
    }
    
}

extension String
{
    // MARK: 1.返回Home的完整路径名
    /**
     *  1.返回Home的完整路径名
     */
    static func homeDir() -> String {
        
        //获取程序的Home目录
        let homeDirectory = NSHomeDirectory()
        return homeDirectory
    }
    // MARK: 2.返回Cache的完整路径名
    /**
     *  2.返回缓存路径的完整路径名 Cache
     */
    static func cacheDir() -> String {
        
        //Cache目录－方法1
        /*
         let cachePaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
         //let cachePath = cachePaths.last
         let cachePath = cachePaths[0]
         return cachePath
         */
        
        //Cache目录－方法2
        let cachePath2 = NSHomeDirectory() + "/Library/Caches"
        return cachePath2
    }
    // MARK: 3.返回Documnets的完整路径名
    /**
     *  3.返回Documnets的完整路径名
     */
    static func DocumnetsDir() -> String {
        
        //获取程序的documentPaths目录
        //方法1
        //        let documentPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        //        let documnetPath = documentPaths[0]
        
        //方法2
        let ducumentPath = NSHomeDirectory() + "/Documents"
        return ducumentPath
    }
    
    // MARK: 4.返回Library的完整路径名
    /**
     *  4.返回Library的完整路径名
     这个目录下有两个子目录：Caches 和 Preferences
     Library/Preferences目录，包含应用程序的偏好设置文件。不应该直接创建偏好设置文件，而是应该使用NSUserDefaults类来取得和设置应用程序的偏好。
     Library/Caches目录，主要存放缓存文件，iTunes不会备份此目录，此目录下文件不会再应用退出时删除
     */
    static func LibraryDir() -> String {
        
        //获取程序的Library目录
        //Library目录－方法1
        //        let libraryPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
        //        let libraryPath = libraryPaths[0]
        //
        //Library目录－方法2
        let libraryPath = NSHomeDirectory() + "/Library"
        return libraryPath
    }
    
    // MARK: 5.返回Tmp的完整路径名
    /**
     *  5.返回Tmp的完整路径名
     用于存放临时文件，保存应用程序再次启动过程中不需要的信息，重启后清空。
     */
    static func TmpDir() -> String {
        
        //方法1
        //let tmpDir = NSTemporaryDirectory()
        
        //方法2
        let tmpDir = NSHomeDirectory() + "/tmp"
        
        return tmpDir
    }
}

